package com.qilu.pe.ui.fragment;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.EventModel;
import com.qilu.pe.dao.bean.Order;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.PeUtil;
import com.qilu.pe.ui.activity.OrderDetailActivity;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 预约下单--预约列表
public class PlaceOrder2Fragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    private RecyclerView rcv_order_list;// 预约订单列表
    private AppCompatEditText et_name;
    private TextView tv_ok, tv_day;
    private LinearLayout ll_time;// 时间
    private Date mTimeFilter;

    private SmartRefreshLayout vRefresh;
    private int mPage = 1, mPageSize = 15;
    private PlaceOrderListAdapter adapter;
    private List<Order> orderList = new ArrayList<>();

    public PlaceOrder2Fragment() {

    }

    public static PlaceOrder2Fragment newInstance(String status) {
        PlaceOrder2Fragment fragment = new PlaceOrder2Fragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Arad.bus.register(this);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        orderList.clear();
        adapter.notifyDataSetChanged();
        vRefresh.setEnableLoadMore(true);
        onLoadMore(vRefresh);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        reqOrderList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)// EventBus事件接收方法
    public void eventMsg(EventModel ev) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_place_order2, container, false);
        rcv_order_list = v.findViewById(R.id.rcv_order_list);

        vRefresh = v.findViewById(R.id.vRefresh);
        View searchBar = LayoutInflater.from(getContext()).inflate(R.layout.layout_search_bar, null, false);
        et_name = searchBar.findViewById(R.id.et_name);
        tv_ok = searchBar.findViewById(R.id.tv_ok);
        tv_day = searchBar.findViewById(R.id.tv_day);
        ll_time = searchBar.findViewById(R.id.ll_time);

        adapter = new PlaceOrderListAdapter(orderList);
        adapter.addHeaderView(searchBar);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_order_list.setLayoutManager(manager);
        rcv_order_list.setAdapter(adapter);

        setListeners();

        vRefresh.setOnRefreshListener(this);
        vRefresh.setOnLoadMoreListener(this);
        vRefresh.autoRefresh();
        return v;
    }

    private void setListeners() {
        setOnClickListener(tv_ok, ll_time);
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

    @Override
    public void onClick(View v) {
        if (v == tv_ok) {// 搜索
            vRefresh.autoRefresh();
        }
        if (v == ll_time) {// 选择时间
            initTimePicker();
            pvTime.show();
        }
    }

    private TimePickerView pvTime;

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
//                Toast.makeText(getActivity(), getTime(date), Toast.LENGTH_SHORT).show();
                Log.i("pvTime", "onTimeSelect");
                tv_day.setText(getTime(date));
                mTimeFilter = date;
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
                Log.i("pvTime", "onTimeSelectChanged");
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择时间")
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private Disposable reqOrderList() {
        String name = et_name.getText().toString().trim();
        String time;
        if (mTimeFilter == null) {
            time = "";
        } else {
            time = new SimpleDateFormat("yyyy-MM-dd").format(mTimeFilter);
        }
        return APIRetrofit.getDefault().reqOrderList(Global.HEADER, name, mPage, mPageSize, time)
                .compose(RxUtil.<BaseResult2<List<Order>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Order>>>() {
                    @Override
                    public void accept(BaseResult2<List<Order>> listBaseResult2) throws Exception {
                        vRefresh.finishRefresh();
                        vRefresh.finishLoadMore();
                        if (listBaseResult2.isSuccess()) {
                            mPage++;
                            orderList.addAll(listBaseResult2.getData());
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtils.showShort(listBaseResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 预约订单列表adapter
    private class PlaceOrderListAdapter extends BaseQuickAdapter<Order, BaseViewHolder> {

        public PlaceOrderListAdapter(List<Order> orders) {
            super(R.layout.item_place_order_list, orders);
        }

        @Override
        protected void convert(BaseViewHolder holder, Order o) {
            TextView tv_name = holder.itemView.findViewById(R.id.tv_name);
            TextView tv_status = holder.itemView.findViewById(R.id.tv_status);
            TextView tv_patient_name = holder.itemView.findViewById(R.id.tv_patient_name);
            TextView tv_order_time = holder.itemView.findViewById(R.id.tv_order_time);
            TextView tv_pay_time = holder.itemView.findViewById(R.id.tv_pay_time);
            TextView tv_ctrl_btn = holder.itemView.findViewById(R.id.tv_ctrl_btn);

            tv_name.setText(o.getProject_name());
            tv_patient_name.setText(o.getName());
            tv_order_time.setText("预约时间:" + o.getTime());
            tv_pay_time.setText("下单时间:" + o.getTime());
            // 订单状态 1待付款,2申请退款,3订单取消,4已退款,5未接单,6运输中,7检验中,8已出报告
            tv_status.setText(PeUtil.getOrderStatus(o.getType()));

            tv_ctrl_btn.setTag(o);
            tv_ctrl_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Order order = (Order) v.getTag();
                    // 查看订单详情
                    Bundle bundle = new Bundle();
                    bundle.putString("title", PeUtil.getOrderStatus(order.getType()));
                    bundle.putString("orderId", order.getId());
                    bundle.putString("orderStatus", order.getType());
                    startActivity(OrderDetailActivity.class, bundle);
                }
            });
        }
    }

}